import json
import os
import socket
import uuid
from datetime import datetime, timedelta
from typing import List, Any
import pandas as pd
from flask import make_response

import tools.config as config


class Tool:
    dataDir = ''

    priceData: List = []

    file = 'sh.json'

    code = ''

    def __init__(self):
        self.dataDir = os.path.dirname(__file__) + "/../file/"
        self.prjectDir = os.path.dirname(__file__) + "/../"

    def readFile(self, fileName):
        file = self.prjectDir + fileName
        data = open(file, encoding='utf-8').read()
        return data

    def getKlineData(self):
        if len(self.klineData) != 0:
            return self.klineData
        self.fillKlineDataFromDF()
        return self.klineData

    def getPriceData(self):
        if len(self.priceData) != 0:
            return self.priceData
        self.fillKlineDataFromDF()
        return self.priceData

    def getRecentNodes(self, recent=100, offset=0):
        """
        :rtype: List[Node]
        """
        data = self.getKlineData()
        if recent == -1:  # 0代表所有
            return data

        end = len(data)
        if recent > end:
            recent = 0
        elif offset != 0:
            recent = end - recent
        else:
            end = recent + offset
        return data[recent:end]

    def getRangeData(self, start=0, offset=..., type='price'):
        """
        :rtype: List[Node]
        """
        data = self.getKlineData()
        if offset is ...:
            offset = len(data)
        ret = data[start:start + offset]
        return ret

    def formatRes(self, res: List, dates: List = ..., point=2):
        if dates is ...:
            dates = []
            klineData = self.getKlineData()
            for item in klineData:
                dates.append(item.date)
        res2 = {}
        for idx in range(len(res)):
            res2[dates[idx]] = round(res[idx], 2)
        return res2

    def getKData(self, fileName='002739.SZ'):
        res = pd.read_csv(self.dataDir + "kline/" + fileName)
        return res

    def log(self, txt, level=20):
        if config.logLevel > level:
            return
        print(txt)

    def dateAdd(self, date, addDays):
        # 将字符串转换为 datetime 对象
        date_obj = datetime.strptime(str(date), "%Y%m%d")
        # 加5天
        new_date_obj = date_obj + timedelta(days=addDays)
        # 将新的日期对象转换回字符串
        new_date_str = new_date_obj.strftime("%Y%m%d")
        return int(new_date_str)

    def getCodeNum(self, nameCode):
        # nameCode: 大洋生物(003017.XSHE)  -> 003017
        code = nameCode.split('(')[1].split('.')[0]
        return code

    def isTestEnv(self):
        computer_name = socket.gethostname()
        return computer_name == 'fw'

    def nowDate(self):
        current_date = datetime.now().strftime("%Y%m%d")
        return int(current_date)

    def result(self, data):
        response = make_response(data)
        # 设置响应请求头
        # response.headers["Access-Control-Allow-Origin"] = '*'  # 允许使用响应数据的域。也可以利用请求header中的host字段做一个过滤器。
        # response.headers["Access-Control-Allow-Methods"] = 'GET'  # 允许的请求方法
        # response.headers["Access-Control-Allow-Headers"] = "x-requested-with,content-type"  # 允许的请求header
        return response

    def getUUID(self):
        return str(uuid.uuid4()).replace('-', '')


tool = Tool()
